package middleware

import (
	"encoding/json"
	"gin/common"
	"gin/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//获取header
		tokenString := ctx.GetHeader("Authorization")
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "缺少参数"})
			ctx.Abort()
			return
		}
		tokenString = tokenString[7:]
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code": 401, "msg": "校验失败"})
			ctx.Abort()
			return
		}
		//通过验证
		redisDb := common.GetRedis()
		user, _ := redisDb.Get("UID" + strconv.Itoa(claims.UserId)).Result()
		var result = model.UserInfo{}
		err = json.Unmarshal([]byte(user), &result)
		//用户是否存在
		if result.Uid == 0 {
			ctx.JSON(http.StatusOK, gin.H{"code": 403, "msg": "token失效"})
			ctx.Abort()
			return
		}
		ctx.Set("user", result)
		ctx.Next()

	}
}
